<!-- 头部框架 -->
<template>
  <!-- 卡片图 -->
  <el-card class="box-card">
    <!-- 顶部添加品牌按钮 -->
    <el-button type="primary" size="default" ic="Pluse" @click="addTrademark"
      style="margin-bottom:10px ;">添加品牌</el-button>
    <!-- 表格 -->
    <el-table border :data="trademarkArr">
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width:100px;height:100px;">
        </template>
      </el-table-column>
      <!-- 删除编辑按钮 -->
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button type="primary" size="small" icon="Edit" @click="$event => updateTrademark(row)"></el-button>
          <!-- 删除按钮 -->
          <el-popconfirm :title="`确定要删除 ${row.tmName}?`" width="250px" icon="Delete" @confirm="removeTradeMark(row.id)">
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器组件 -->
    <el-pagination @size-Change="sizeChange" @current-change="getHasTrademark" :pager-count="9"
      v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total, " :total="total">
    </el-pagination>
  </el-card>
  <!-- 弹出对话框组件：修改品牌 -->
  <!-- v-model 控制用户控制对话框显示隐藏 -->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
    <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- 上传login图片 -->
        <el-upload class="avatar-uploader" action="api/admin/product/fileUpload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 确定 取消按钮 -->
    <!-- 具名插槽 ：footer -->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
// 引入组合式APl函数ref
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqHasTradeMark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import type { Records, TradeMark, TradeMarkResponseData } from "@/api/product/trademark/type"
// 当前页码
let pageNo = ref<number>(1);
// 每一页展示多少条数据 
let limit = ref<number>(3);
// 存储已有品牌数据总数
let total = ref<number>(0);
// 存储已有品牌数据
let trademarkArr = ref<Records>([])
//控制对话框显示隐藏按钮 
let dialogFormVisible = ref<boolean>(false)
// 定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
// 获取el-FORM 组件实施
let formRef = ref();
// 获取已有品牌的接口封装为一个函数：在任何情况下向获取数据，调取次函数即可
const getHasTrademark = async (pager = 1) => {
  let result: TradeMarkResponseData = await reqHasTradeMark(pageNo.value, limit.value);
  if (result.code == 200) {
    // 存储已有品牌总个数
    total.value = result.data.total,
      trademarkArr.value = result.data.records;
  }
  console.log(result);
}
// 组件挂载完毕钩子 发一次请求数据 获取第一页 第二页 第三页数据
onMounted(() => {
  getHasTrademark();
});
/*  无效代码
分页器当前页码发送改变就触发函数
const changePageNo = ()=>{
  // 当前页码发送变化的时候再次发起请求获取对应以有数据进行展示
  getHasTrademark();
}
*/
// 当下拉菜单发送改变会触发此方法
const sizeChange = () => {
  // 当数据发送变化页码号归一
  pageNo.value = 1;
  getHasTrademark()
}
// 添加按钮 点击显示弹出
const addTrademark = () => {
  dialogFormVisible.value = true;
  //清空收集数据
  trademarkParams.id = 0;
  trademarkParams.tmName = '';
  trademarkParams.logoUrl = ''
  nextTick(() => {
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl')
  })
}
// 修改已有品牌的按钮回调
// row 为当前已有的品牌
const updateTrademark = (row: TradeMark) => {
  // 对话框显示
  dialogFormVisible.value = true;
  // 收集展示出已有数据
  // 合并对象
  Object.assign(trademarkParams, row);
}
// 对话框底部按钮取消按钮
const cancel = () => {
  // 对话框隐藏
  dialogFormVisible.value = false;
}
const confirm = async () => {
  //在发请求之前对表单进行校验
  await formRef.value.validate();
  let result: any = await reqAddOrUpdateTrademark(trademarkParams);
  // 添加品牌 或者 修改品牌
  if (result.code == 200) {
    // 关闭对话框
    dialogFormVisible.value = false;
    // 随后弹出成功的对话框
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功'
    });
    // 再次发起请求获取全部品牌数据
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    // 添加失败
    ElMessage({
      type: "error",
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败'
    });
    // 关闭对话框
    dialogFormVisible.value = false;
  }
}
// 上传图片组件-上传图片之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 钩子是在上传图片之前触发
  console.log(rawFile)
  if (rawFile.type !== 'image/jpeg' || rawFile.type == 'image/gif') {
  } else {
    ElMessage({
      type: "error",
      message: "上传文件必须小于4M"
    })
    return false;
  }
}
// 图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // response即为当前这次上传图片
  trademarkParams.logoUrl = response.data;
  // 图片上传成功清除图片校验
  formRef.value.clearValidate("logoUrl")
}
// 品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack();
  } else {
    //校验未通过返回滴提示
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
// 品牌LOgo 图片的自定义校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  // 如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
// 表单验证
const rules = {
  tmName: [{ required: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'change', validator: validatorLogoUrl }]

}
// 气泡确定框确定按钮问题
const removeTradeMark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if(result.code == 200) {
    // 删除成功提示
    ElMessage({
      type: "success",
      message: "删除品牌成功"
    })
    // 再次获取数据
    getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value -1);
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败"
    })
  }
}
</script>
<style scoped>
.el-pagination {
  margin-top: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>